package com.mpgame.database.mysql.manager;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.mpgame.database.mysql.config.MySqlCfg;
import com.mpgame.database.mysql.utils.DataSourceUtil;
import com.mpgame.database.mysql.utils.MyBatisUtil;
import com.mpgame.utils.Log;

public class MySqlMgr {
    private static volatile MySqlMgr instance;
    private static final Map<String, Boolean> initializedDatabases = new ConcurrentHashMap<>();

    private MySqlMgr() {}

    public static MySqlMgr getInstance() {
        if (instance == null) {
            synchronized (MySqlMgr.class) {
                if (instance == null) {
                    instance = new MySqlMgr();
                }
            }
        }
        return instance;
    }

    public void init(MySqlCfg cfg, String databaseName) {
        if (initializedDatabases.getOrDefault(databaseName, false)) {
            Log.warn("MySQL数据库" + databaseName + "已初始化完成，不可重复初始化！");
            return;
        }
        try{
            DataSourceUtil.init(cfg, databaseName);
            MyBatisUtil.init(cfg, databaseName);
            initializedDatabases.put(databaseName, true);
            Log.info("MySQL数据库" + databaseName + "初始化完成");
        }catch(Exception e){
            Log.err("MySQL数据库" + databaseName + "初始化失败：" + e.getMessage());
            throw new RuntimeException("MySQL数据库" + databaseName + "初始化失败", e);
        }
    }
    
    public void initAll() {
        initVerify();
        initGame();
    }
    public void initVerify(){
        Log.info("使用验证服务器配置初始化MySQL Verify数据库...");
        init(MySqlCfg.getVerify(), "verify");
    }
    public void initGame(){
        Log.info("使用游戏服务器配置初始化MySQL Game数据库...");
        init(MySqlCfg.getDefault(), "game");
    }

    public void shutdown() {
        DataSourceUtil.closeAll();
        MyBatisUtil.close();
        initializedDatabases.clear();
        Log.info("所有MySQL数据库连接已关闭");
    }

    public boolean isVerifyInitialized() {
        return initializedDatabases.getOrDefault("verify", false);
    }
    
    public boolean isGameInitialized() {
        return initializedDatabases.getOrDefault("game", false);
    }
    public boolean isAllInitialized() {
        return isVerifyInitialized() || isGameInitialized();
    }
    
    public boolean testConnection() {
        return DataSourceUtil.testConnection();
    }
    public boolean testConnection(String databaseName){
        return DataSourceUtil.testConnection(databaseName);
    }
    
}